package net.hvacapp.cmvrfforandroid.ui.mine;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.TextView;

import com.mirror.android.common.util.ScreenUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.model.GetUserProfileDataResp;
import net.hvacapp.cmvrfforandroid.model.UserProfileData;
import net.hvacapp.cmvrfforandroid.ui.EventBus.NewMessageRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.EventBus.UserListRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.ViewDetailActivity;
import net.hvacapp.cmvrfforandroid.ui.fragment.BaseFragment;
import net.hvacapp.cmvrfforandroid.ui.listener.OnStateChangeListener;
import net.hvacapp.cmvrfforandroid.ui.mine.model.GetSuggestionDataResp;
import net.hvacapp.cmvrfforandroid.ui.mine.model.NoticeData;
import net.hvacapp.cmvrfforandroid.ui.mine.model.SuggestionData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.DateTimeUtils;
import net.hvacapp.cmvrfforandroid.utils.WindowUtils;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.OnRefreshListener;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenu;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuCreator;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuItem;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuLayout;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuListView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
@EFragment(R.layout.fragment_suggestion_list)
public class SuggestionListFragment extends BaseFragment implements OnStateChangeListener {


    @ViewById(R.id.lv_user)
    SwipeMenuListView mUserLv;
    @FragmentArg
    int typeValue;

    private int beginIndex = 0;
    private int endIndex = 0;

    private Dialog mProgressDlg;

    private QuickAdapter<SuggestionData> mQuickAdapter;

    public SuggestionListFragment() {
        // Required empty public constructor
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

        }
    }

    @Override
    public void onStateChange() {
        if (this.isAdded()){

        }
    }

    @AfterViews
    public void init(){
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<SuggestionData>(getActivity(),R.layout.notice_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, SuggestionData item) {
                    helper.setVisible(R.id.iv_navi, true);
//                    helper.setVisible(R.id.iv_new, false);
                    helper.setText(R.id.tv_title, item.getTitle());
                    helper.setText(R.id.tv_info, item.getContent());
                    helper.setText(R.id.tv_date, DateTimeUtils.getDate(item.getTime()));
                    helper.setText(R.id.tv_from, item.getFrom());
                    if (typeValue != 1) {
                        if (item.getViewed() == 1) {
                            helper.setVisible(R.id.iv_new, false);
                        }
                        else {
                            helper.setVisible(R.id.iv_new, true);
                        }
                    }
                    else {
                        helper.setVisible(R.id.iv_new, false);
                    }

//                    helper.setText(R.id.tv_title,item.getUserName())
//                            .setText(R.id.tv_description,item.getName());
                }
            };
        }

        mUserLv.setAdapter(mQuickAdapter);

        //可以删除自提意见
        if (typeValue == 1) {
            // 设置左侧滑menu
            SwipeMenuCreator menuCreator = new SwipeMenuCreator() {

                @Override
                public void create(SwipeMenu menu) {
                    SwipeMenuItem menuItem = new SwipeMenuItem(getActivity());
                    menuItem.setBackground(new ColorDrawable(Color.parseColor("#FFBA7F")));
                    menuItem.setWidth((int) ScreenUtils.dpToPx(getActivity(), 80));
                    menuItem.setTitleColor(getResources().getColor(R.color.cm_navigation_red_color));
                    menuItem.setTitleSize(14);
                    menu.addMenuItem(menuItem);
                    menuItem.setTitle("删除");
                }
            };
            mUserLv.setMenuCreator(menuCreator);
        }



        initData();

        initEvent();
    }


    private void initEvent() {
        mUserLv.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                // 下拉刷新
                beginIndex = 0;
                endIndex = Constant.PAGE_COUNT - 1;
                loadALLSuggestion(beginIndex, endIndex);
            }

            @Override
            public void onPullUpRefresh() {
                // 上拉加载
                beginIndex = mQuickAdapter.getCount();
                endIndex = beginIndex + Constant.PAGE_COUNT - 1;
                loadALLSuggestion(beginIndex, endIndex);
            }
        });

        mUserLv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(SwipeMenuLayout swipeMenuLayout, int position, SwipeMenu menu, int index) {
                SuggestionData data = mQuickAdapter.getItem(position);
                deleteOneSuggestion(data);

                return true;
            }
        });

        mUserLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SuggestionData data = (SuggestionData) parent.getItemAtPosition(position);
                viewOneSuggestion(data.getGuidId());
                Intent intent = new Intent(getActivity(), AnnotationUtil.get(ViewDetailActivity.class));
                intent.putExtra("type", 1);
                intent.putExtra("title", data.getTitle());
                intent.putExtra("info", data.getFrom() + " " + DateTimeUtils.getDate(data.getTime()));
                intent.putExtra("content", data.getContent());
                intent.putExtra("id", data.getGuidId());
                startActivity(intent);
            }
        });

    }

    private void initData() {
        beginIndex = 0;
        endIndex = Constant.PAGE_COUNT - 1;
        loadALLSuggestion(beginIndex, endIndex);
    }

    public void refreshData() {
        loadALLSuggestion(beginIndex, endIndex);
    }


    private void loadALLSuggestion(final int begin, int end) {
        Map<String, Object> param = new HashMap<>();
        param.put("os", typeValue);
        param.put("si", begin);
        param.put("ei", end);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_SUGGESTION, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetSuggestionDataResp>() {
            @Override
            public void onSuccess(GetSuggestionDataResp obj) {
                // 成功
                if (begin == 0) {
                    mQuickAdapter.clear();
                }
                mQuickAdapter.addAll(obj.getGetSuggestionResult());
                mUserLv.onRefreshComplete();
            }

            @Override
            public void onFailure(String response) {
                mUserLv.onRefreshComplete();
            }

        });

    }

    /**
     *  阅读一条意见
     *
     *  @param guidId
     */
    private void viewOneSuggestion(String guidId) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", guidId);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_VIEW_ONE_SUGGESTION, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetSuggestionDataResp>() {
            @Override
            public void onSuccess(GetSuggestionDataResp obj) {
                // 成功，刷新数据
                EventBus.getDefault().post(new NewMessageRefreshEvent());
            }

            @Override
            public void onFailure(String response) {

            }

        });
    }

    private void deleteOneSuggestion (final SuggestionData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", data.getGuidId());

        mProgressDlg = new Dialog(getActivity(), R.style.dialog);
        mProgressDlg.setContentView(R.layout.progressbar_dialog);
        mProgressDlg.setCanceledOnTouchOutside(false);
        Window window = mProgressDlg.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        int width = WindowUtils.getScreenWidth(getActivity());
        lp.width = (int) (0.6 * width);

        TextView titleTxtv = (TextView) mProgressDlg.findViewById(R.id.tvLoad);

        titleTxtv.setText("删除意见中...");
        mProgressDlg.show();

        BasicHttpClient.httpDeleteAsync(HttpConstant.HTTP_DELETE_ONE_SUGGESTION, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetUserProfileDataResp>() {
            @Override
            public void onSuccess(GetUserProfileDataResp obj) {
                // 成功，刷新数据
                mProgressDlg.dismiss();
                mQuickAdapter.remove(data);
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showToast("意见删除失败，请重试！");
            }

        });

    }


}

